import React, { useState, useEffect } from 'react';
import { Col, Form, Row } from 'antd';
import { formItemDefaultLayout, formUtils, TjFormDefaultProps } from './helper';
import { TjFormItem } from './TjFormItem';
import type { Store } from 'antd/lib/form/interface';
import type { ColProps, FormProps, RowProps } from 'antd';
import type { ITjFormItemProps } from './TjFormItem';
import type { ReactNode } from 'react';
import _ from 'lodash';
import './index.less';

const TjForm: React.FC<ITjFormProps> = (props) => {
  const [form] = props.form ? [props.form] : Form.useForm();
  const [formLayout, setFormLayout] = useState<LayoutType>();
  const [initialValues] = useState<any>(
    formUtils.handleInitialValues(props.initialValues, props.items),
  );
  function buildBody() {
    if (props.useGrid) {
      let gridRowConfig: RowProps = TjFormDefaultProps.useGrid.row;
      let gridColConfig: ColProps = TjFormDefaultProps.useGrid.col;

      if (_.isObject(props.useGrid)) {
        const row = _.get(props.useGrid, 'row', null);
        gridRowConfig = _.merge({}, gridRowConfig, row);
        const col = _.get(props.useGrid, 'col', null);
        gridColConfig = _.merge({}, gridColConfig, col);
      }

      return (
        <Row {...gridRowConfig}>
          {items.length > 0 &&
            items.map((item, index) => {
              const colProp = item.col ? item.col : gridColConfig;
              return (
                <Col {...colProp} key={formUtils.getItemKey(item, index)}>
                  <TjFormItem {...item} form={form} />
                </Col>
              );
            })}
        </Row>
      );
    } else {
      return items.map((item, index) => {
        return <TjFormItem {...item} form={form} key={formUtils.getItemKey(item, index)} />;
      });
    }
  }

  function handleLayout() {
    const layout = props.layout || 'horizontal';
    const obj: LayoutType = {
      layout,
      labelCol: props.labelCol ? props.labelCol : (formItemDefaultLayout as any)[layout].labelCol,
      wrapperCol: props.wrapperCol
        ? props.wrapperCol
        : (formItemDefaultLayout as any)[layout].wrapperCol,
    };
    setFormLayout(obj);
  }

  function handleFinish(values: Store) {
    // 这里处理去除空格之类的
    if (props.onFinish) {
      props.onFinish(values);
    }
  }

  useEffect(() => {
    handleLayout();
  }, []);

  const { items, labelCol, wrapperCol, layout, useGrid, ...stdProps } = props;

  return (
    <Form
      {...stdProps}
      {...formLayout}
      form={form}
      initialValues={initialValues}
      className="tj-form"
      onFinish={handleFinish}
    >
      {props.header && <div className="tj-form-header">{props.header}</div>}
      {buildBody()}
      {props.footer && <div className="tj-form-footer">{props.footer}</div>}
    </Form>
  );
};

type LayoutType = {
  labelCol: ITjFormProps['labelCol'];
  wrapperCol: ITjFormProps['wrapperCol'];
  layout: ITjFormProps['layout'];
};

type GridOptionsType = {
  row?: RowProps;
  col?: ColProps;
};

export interface ITjFormProps extends FormProps {
  /**
   *  表单项
   */
  items: ITjFormItemProps[];
  /**
   *  表单使用grid布局
   */
  useGrid?: Boolean | GridOptionsType;
  /**
   * 头部
   * 插槽属性
   */
  header?: ReactNode;
  /**
   * 底部
   * 插槽属性
   */
  footer?: ReactNode;
}

export { TjForm };
